package com.tinckay.common.util;

import com.tinckay.entity.po.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;


/**
 * @Author: Jean
 * @Desc: Shiro操作工具类
 * @Date: 2018/10/23 17:18
 */
public class ShiroUtils {


    /**
     * 角色标识
     * 管理员 admin
     * 普通用户 user
     * 运输人员 transportDriver
     * 泵车操作人员 pumpOperator
     * 监测端用户 monitor
     */
    public static final String ADMIN = "admin";

    /**
     * 当前登陆用户id
     *
     * @return
     */
    public static Long getCurrentUserId() {
        User currentUser = getCurrentUser();
        return currentUser == null ? null : currentUser.getId();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public static User getCurrentUser() {
        Subject subject = getSubject();
        return subject == null ? null : (User) subject.getPrincipal();
    }

    /**
     * 登陆
     *
     * @param token
     */
    public static void login(AuthenticationToken token) {
        getSubject().login(token);
    }

    /**
     * 检验是否管理员
     *
     * @return
     */
    public static boolean isAdmin() {
        return SecurityUtils.getSubject().hasRole(ADMIN);
    }

    /**
     * 获取shiro指定的sessionKey
     */
    public static <T> T getSessionAttr(String key) {
        Session session = getSession();
        return session != null ? (T) session.getAttribute(key) : null;
    }

    public static Session getSession() {
        return getSubject().getSession();
    }

    public static void removeAttr(String key) {
        getSession().removeAttribute(key);
    }

}
